import cookielib, urllib, urllib2, re

class VkontakteNotLoggedInError(Exception):
    pass

class VkontakteAuth:
    def __init__(self):
        self._vkontakte_cookie = cookielib.CookieJar()
        self._logged_in = False
        self._vkontakte_id = -1
        
    def get_cookie(self):
        if not self.IsLoggedIn():
            raise VkontakteNotLoggedInError()
        return self._vkontakte_cookie;
    
    def IsLoggedIn(self):
        return self._logged_in
    
    def GetID(self):
        return self._vkontakte_id
    
    def Login(self, login, password):
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self._vkontakte_cookie))
        auth_data = {"email": login, "pass": password}
        response = opener.open("http://vkontakte.ru/login.php", urllib.urlencode(auth_data))
        match = re.search(r'vkontakte\.ru/id(\d+)', response.geturl())
        if match:
            self._logged_in = True
            self._vkontakte_id = int(match.group(1))
        else:
            self._logged_in = False
        
        return self._logged_in
    